package com.jincp.common.utils;

import android.media.MediaScannerConnection;
import android.net.Uri;

import com.jincp.common.base.BaseApplication;

/**
 * @ProjectName: AyokaClient.
 * @ClassName: MediaScannerManager.
 * @Description: .
 * @Author: jincp.
 * @CreateDate: 2019/11/28 14:18.
 */

public class MediaScannerManager {

    private static MediaScannerManager instance;

    public static MediaScannerManager getInstance() {
        if (instance == null) {
            instance = new MediaScannerManager();
        }
        return instance;
    }

    private MediaScannerConnection mediaScanConn = null;
    private MediaScannerClient client = null;

    private String filePath = null;
    private String fileType = null;

    /**
     * 然后调用MediaScanner.scanFile("path");
     */
    public MediaScannerManager() {
        if (client == null) {
            client = new MediaScannerClient();
        }
        if (mediaScanConn == null) {
            mediaScanConn = new MediaScannerConnection(BaseApplication.getInstance(), client);
        }
    }

    private class MediaScannerClient implements MediaScannerConnection.MediaScannerConnectionClient {

        public void onMediaScannerConnected() {
            if (filePath != null) {
                mediaScanConn.scanFile(filePath, fileType);
            }
            filePath = null;
            fileType = null;
        }

        public void onScanCompleted(String path, Uri uri) {
            mediaScanConn.disconnect();
        }
    }

    /**
     * 更新相册-扫描文件标签信息
     * @param filePath 文件路径
     * @param fileType 文件类型 "image/jpeg"
     */

    public void scanFile(String filePath, String fileType) {
        this.filePath = filePath;
        this.fileType = fileType;
        //连接之后调用MusicSannerClient的onMediaScannerConnected()方法
        mediaScanConn.connect();
    }
}
